"use client"

import { useEffect, useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { Volume2, VolumeX, Pause, Play } from "lucide-react"
import { Slider } from "@/components/ui/slider"

interface AudioPlayerProps {
  url: string
  isActive?: boolean
  onStatusChange?: (status: string) => void
}

export function AudioPlayer({ url, isActive = true, onStatusChange }: AudioPlayerProps) {
  const audioRef = useRef<HTMLAudioElement>(null)
  const playerRef = useRef<any>(null)  // flv.js player
  const [playing, setPlaying] = useState(isActive)
  const [volume, setVolume] = useState(1)

  // 初始化播放器的异步函数
  const initFlvPlayer = async () => {
    console.log("【DEBUG】开始初始化播放器，url:", url); // ✅ 验证是否进入函数

    try {
      const flvjs = await import("flv.js");

      if (!audioRef.current || !url || !flvjs.isSupported()) {
        console.warn("【WARN】无法初始化播放器，条件不满足");
        return null;
      }

      const config = {
        type: "flv",
        url,
        autoCleanupMaxBackwardDuration: 5,
        autoCleanupMinBackwardDuration: 2,
        autoCleanupSourceBuffer: true,
        enableStatisticsInfoReport: true,
        hasVideo: false, // 禁用视频流
        disableAudioTimestampCorrection: true, // 禁用音频时间戳修正
      };

      const player = flvjs.createPlayer(config);
      player.attachMediaElement(audioRef.current);
      player.load();

      player.on(flvjs.Events.LOADING_COMPLETE, () => {
        player.play().catch((err) => {
          console.error("【ERROR】播放失败:", err);
        });
        setPlaying(true);
        onStatusChange?.("playing");
      });

      player.on(flvjs.Events.ERROR, (errorType, errorDetail) => {
        console.error(`【ERROR】播放器错误 (${url}):`, errorType, errorDetail);
        onStatusChange?.("error");
      });

      player.on(flvjs.Events.PLAYBACK_STATE_CHANGE, (state: string) => {
        if (state === "ENDED") {
          setPlaying(false);
          onStatusChange?.("paused");
        }
      });

      return player;

    } catch (error) {
      console.error(`【ERROR】动态导入 flv.js 失败或播放器初始化失败 (${url}):`, error);
      return null;
    }
  };

  // 初始化播放器
  useEffect(() => {
    let isMounted = true;

    const setupPlayer = async () => {
      const player = await initFlvPlayer();
      if (isMounted && player) {
        playerRef.current = player;
      }
    };

    if (url) {
      setupPlayer();
    }

    return () => {
      isMounted = false;
      if (playerRef.current) {
        playerRef.current.destroy();
        playerRef.current = null;
      }
    };
  }, [url]);

  // 控制音量
  useEffect(() => {
    const audio = audioRef.current;
    if (audio) {
      audio.volume = volume;
    }
  }, [volume]);

  // 控制播放/暂停
  useEffect(() => {
    const player = playerRef.current;
    if (!player) return;

    if (playing) {
      player.play().catch((e) => console.error("播放失败:", e));
      onStatusChange?.("playing");
    } else {
      player.pause();
      onStatusChange?.("paused");
    }
  }, [playing, onStatusChange]);

  const togglePlay = () => setPlaying((prev) => !prev);

  const handleVolumeChange = (val: number[]) => {
    const v = val[0];
    setVolume(v);
    if (audioRef.current) {
      audioRef.current.volume = v;
    }
  };

  return (
    <div className="flex items-center gap-4 bg-muted px-4 py-2 rounded-md shadow-inner w-full max-w-md">
      {/* 控制按钮 */}
      <Button variant="ghost" size="icon" onClick={togglePlay}>
        {playing ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
      </Button>

      {/* 音量控制 */}
      <div className="flex items-center gap-2 w-full">
        {volume > 0 ? <Volume2 className="w-4 h-4" /> : <VolumeX className="w-4 h-4" />}
        <Slider
          value={[volume]}
          max={1}
          step={0.01}
          onValueChange={handleVolumeChange}
          className="w-full"
        />
      </div>

      {/* 隐藏的 audio 元素用于 flv.js 播放音频（需要绑定到 audio 元素） */}
      <audio
        ref={audioRef}
        muted={false}
        autoPlay={true}
        controls
        style={{ display: "none" }}
      />
    </div>
  );
}
